package com.kaiwukj.android.ufamily.mvp.ui.page.home.service;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerServiceComponent;
import com.kaiwukj.android.ufamily.di.module.ServiceModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.GlobalEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.ServiceEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.helper.ServiceHelperResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.helper.ServiceHistoryEntry;
import com.kaiwukj.android.ufamily.mvp.http.entity.multi.ServiceItemMultiEntity;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.ServiceGroupResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.ServiceResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.service.ServiceContract;
import com.kaiwukj.android.ufamily.utils.ServiceHistoryStore;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ServiceFragment extends BaseMvpFragment<ServicePresenter> implements ServiceContract.View {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.container_left)
    ViewGroup containerLeft;
    @BindView(R.id.container_right)
    ViewGroup containerRight;
    //@BindView(R.id.tv_right)
    // TextView tvRight;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_service_subject)
    RecyclerView rvServiceSubject;
    @BindView(R.id.rv_content)
    RecyclerView rvContent;
    @BindView(R.id.empty_view)
    QMUIEmptyView emptyView;

    private ServiceSubjectAdapter mSubjectAdapter;
    private ServiceContentAdapter mContentAdapter;

    private boolean isNeedRefresh = false;

    @OnClick(R.id.container_right)
    void onRightClick() {

        if (getApp().getUserInfo().getHkeeperId() < 0) {
            ARouter.getInstance().build(ARouterUrlKt.MineKeeperContainerUrl).navigation();
        } else {
            ARouter.getInstance().build(ARouterUrlKt.KeeperIndexUrl)
                    .navigation();
        }
        // ChatActivity.startKeeperChat(getContext(), getApp().getUserInfo().getKeeperHxName());
    }


    public static ServiceFragment newInstance() {
        return new ServiceFragment();
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        super.setupFragmentComponent(appComponent);
        //DaggerSear
        DaggerServiceComponent.builder()
                .appComponent(appComponent)
                .serviceModule(new ServiceModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_service;
    }

    @Override
    protected void initView() {
        tvTitle.setText("服务");
        containerLeft.setVisibility(View.GONE);
       /* if (StringUtils.isEmpty(getApp().getUserInfo().getKeeperHxName())) {
            containerRight.setVisibility(View.GONE);
        } else {
            containerRight.setVisibility(View.VISIBLE);
        }*/
        rvServiceSubject.setLayoutManager(new LinearLayoutManager(getContext()));
        mSubjectAdapter = new ServiceSubjectAdapter();
        rvServiceSubject.setAdapter(mSubjectAdapter);
        LinearLayoutManager contentLayoutManager = new LinearLayoutManager(getContext());
        rvContent.setLayoutManager(contentLayoutManager);
        mContentAdapter = new ServiceContentAdapter();
        rvContent.setAdapter(mContentAdapter);

        // vpContent.setAdapter(mFragmentAdapter);

        mSubjectAdapter.setOnItemClickListener((adapter, view, position) ->
        {
            // rvContent.scrollToPosition(position);
            contentLayoutManager.scrollToPositionWithOffset(position, 0);
            mSubjectAdapter.checkItem(position);
        });
        mSubjectAdapter.checkItem(0);

        rvContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                // int lastItemPosition = 0;
                int firstItemPosition = 0;
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    //lastItemPosition = linearManager.findLastVisibleItemPosition();
                    firstItemPosition = linearManager.findFirstVisibleItemPosition();
                }
                mSubjectAdapter.checkItem(firstItemPosition);
            }
        });

        refreshLayout.setOnRefreshListener(refreshLayout ->
                mPresenter.fetchServiceGroup());

    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (isNeedRefresh) {
            isNeedRefresh = false;
            emptyView.show(true);
            mPresenter.fetchServiceGroup();
           /* if (StringUtils.isEmpty(getApp().getUserInfo().getKeeperHxName())) {
                containerRight.setVisibility(View.GONE);
            } else {
                containerRight.setVisibility(View.VISIBLE);
            }*/
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        //setPaddingTop(R.id.container_header);
        //showLoading();
        emptyView.show(true);
        mPresenter.fetchServiceGroup();
    }

    @Override
    public void onTaskErr(int taskId) {
        super.onTaskErr(taskId);
        // hideLoading();
        emptyView.hide();
        refreshLayout.finishRefresh(false);
    }

    @Override
    public void onFetchServiceGroup(ServiceHelperResult result) {
        //hideLoading();
        emptyView.hide();
        List<ServiceItemMultiEntity> parentData = new ArrayList<>();
        refreshLayout.finishRefresh(true);
        ServiceItemMultiEntity history = getHistoryData();
        if (history.getHistoryEntry() != null && history.getHistoryEntry().size() > 0) {
            parentData.add(history);
        }
        if (result.getStatus().isOwner()) {
            parentData.add(getPropertyData());
        }
        parentData.add(getCommunityServiceData());
        parentData.add(getGMData());


        for (ServiceGroupResult r : result.getGroupResults()) {
            ServiceItemMultiEntity multiEntity = new ServiceItemMultiEntity(ServiceItemMultiEntity.ITEM_SERVICE);
            multiEntity.setServiceResult(r);
            parentData.add(multiEntity);
        }
        mSubjectAdapter.setList(parentData);
        mContentAdapter.setList(parentData);

        if (mSubjectAdapter.getItemCount() == 0) {
            //emptyView.setVisibility(View.VISIBLE);
            emptyView.show("该小区未找到服务项目", "");
        } else {
            //  emptyView.setVisibility(View.GONE);
            emptyView.hide();
        }
        // mFragmentAdapter.notifyDataSetChanged();
    }

    private ServiceItemMultiEntity getHistoryData() {
        List<ServiceHistoryEntry> list = ServiceHistoryStore.getList();
        ServiceItemMultiEntity entity = new ServiceItemMultiEntity(ServiceItemMultiEntity.ITEM_HISTORY);
        Collections.reverse(list);
        entity.setHistoryEntry(list);
        return entity;
    }

    private ServiceItemMultiEntity getPropertyData() {
        ServiceGroupResult serviceGroupResult = new ServiceGroupResult();
        serviceGroupResult.setType(-1);
        serviceGroupResult.setLabel("物业服务");
        serviceGroupResult.setId(R.mipmap.banner_service_wuye);

        List<ServiceResult> children = new ArrayList<>();
        children.add(new ServiceResult(R.mipmap.ic_service_item_door, ServiceHistoryEntry.PROPERTY_DOOR, "开门"));
        children.add(new ServiceResult(R.mipmap.ic_service_item_report, ServiceHistoryEntry.PROPERTY_REPORT, "报修"));
        children.add(new ServiceResult(R.mipmap.ic_service_item_wallet, ServiceHistoryEntry.PROPERTY_FEE, "缴费"));
        children.add(new ServiceResult(R.mipmap.ic_service_item_park, ServiceHistoryEntry.PROPERTY_PARK, "停车"));
        //  children.add(new ServiceResult(R.mipmap.ic_service_item_comment, "评价"));
        children.add(new ServiceResult(R.mipmap.ic_service_item_notice, ServiceHistoryEntry.PROPERTY_NOTICE, "物业公告"));
        children.add(new ServiceResult(R.mipmap.ic_service_item_complaint, ServiceHistoryEntry.PROPERTY_TOUSU, "投诉"));

        serviceGroupResult.setChildren(children);
        ServiceItemMultiEntity itemMultiEntity = new ServiceItemMultiEntity(ServiceItemMultiEntity.ITEM_PROPERTY);
        itemMultiEntity.setServiceResult(serviceGroupResult);
        return itemMultiEntity;
    }

    private ServiceItemMultiEntity getCommunityServiceData() {
        ServiceGroupResult serviceGroupResult = new ServiceGroupResult();
        serviceGroupResult.setType(-2);
        serviceGroupResult.setLabel("社区服务");
        // serviceGroupResult.setId(R.mipmap.banner_service_gm);

        List<ServiceResult> children = new ArrayList<>();
        children.add(new ServiceResult(R.mipmap.ic_service_community_item_news, ServiceHistoryEntry.COMMUNITY_NEWS, "社区资讯"));
        children.add(new ServiceResult(R.mipmap.ic_service_community_item_zyzm, ServiceHistoryEntry.COMMUNITY_ZYZM, "志愿招募"));
        children.add(new ServiceResult(R.mipmap.ic_service_community_item_guide, ServiceHistoryEntry.COMMUNITY_EVENT, "办事指南"));

        serviceGroupResult.setChildren(children);

        ServiceItemMultiEntity itemMultiEntity = new ServiceItemMultiEntity(ServiceItemMultiEntity.ITEM_COMMUNITY_SERVICE);
        itemMultiEntity.setServiceResult(serviceGroupResult);
        return itemMultiEntity;
    }

    private ServiceItemMultiEntity getGMData() {
        ServiceGroupResult serviceGroupResult = new ServiceGroupResult();
        serviceGroupResult.setType(-2);
        serviceGroupResult.setLabel("家装服务");
        serviceGroupResult.setId(R.mipmap.banner_service_gm);

        List<ServiceResult> children = new ArrayList<>();
        children.add(new ServiceResult(R.mipmap.ic_service_gm_item_mfsj, ServiceHistoryEntry.GM_MFSJ, "免费设计"));
        children.add(new ServiceResult(R.mipmap.ic_service_gm_item_xfzx, ServiceHistoryEntry.GM_XFZX, "新房装修"));
        children.add(new ServiceResult(R.mipmap.ic_service_gm_item_jfgz, ServiceHistoryEntry.GM_JFGZ, "旧房改造"));
        children.add(new ServiceResult(R.mipmap.ic_service_gm_item_mfbj, ServiceHistoryEntry.GM_MFBJ, "免费报价"));
        children.add(new ServiceResult(R.mipmap.ic_service_gm_item_zxzb, ServiceHistoryEntry.GM_ZXZB, "装修直播"));

        serviceGroupResult.setChildren(children);

        ServiceItemMultiEntity itemMultiEntity = new ServiceItemMultiEntity(ServiceItemMultiEntity.ITEM_GM);
        itemMultiEntity.setServiceResult(serviceGroupResult);
        return itemMultiEntity;
    }

    @Subscribe
    public void onGlobalEvent(GlobalEvent event) {
        if (event.getCode() == GlobalEvent.REFRESH) isNeedRefresh = true;
    }

    @Subscribe
    public void onServiceEvent(ServiceEvent event) {
        if (event.getCode() == ServiceEvent.HISTORY_UPDATE) {
            ServiceItemMultiEntity history = getHistoryData();
            if (mContentAdapter.hasHistory()) {
                mContentAdapter.updateHistory(history.getHistoryEntry());
            } else {
                mContentAdapter.addData(0, history);
                mSubjectAdapter.addData(0, history);
            }
        }
    }

}
